import {ChangeEventHandler, FC, useEffect, useState} from "react";
import {useNavigate} from "react-router-dom";
import DGConnect from "../../../sources/DGConnect.ts";
import {Util} from "../../../sources/Util.ts";
import DGDialogLayout from "../../../components/DGDialogLayout/DGDialogLayout.tsx";
import DGTextView from "../../../components/DGTextView.tsx";
import {Box, Button, FormControl, FormHelperText, Input, InputAdornment, InputLabel, TextField} from "@mui/material";
import DGDrawerLayout from "../../../components/DGDrawerLayout/DGDrawerLayout.tsx";
import DGToast from "../../../components/DGToast.tsx";
import {AlertColor} from "@mui/material/Alert/Alert";
import IconButton from "@mui/material/IconButton";
import {Visibility, VisibilityOff} from "@mui/icons-material";
import AppProvider from "../../../sources/AppProvider.ts";

interface DGLoginPasswordProps {
    state: boolean,
    switchView: (text: string) => void
}


interface DGToastProps {
    state: boolean,
    severity: AlertColor,
    text: string
}

const DGLoginPassword: FC<DGLoginPasswordProps> = ({state, switchView}) => {
    // 全局上下文
    const App = AppProvider.useAppContext();
    // 全局主题上下文
    const ThemeContext = AppProvider.useAppThemeContext();
    // 路由跳转
    const router = useNavigate();
    // 密码信息
    const [password, setPassword] = useState("");
    // 密码显示状态
    const [showPwd, setShowPwd] = useState(false);
    // 密码错误信息
    const [error, setError] = useState({state: false, text: ""});
    // 加载状态
    const [loading, setLoading] = useState(false);
    // Toast 弹窗
    const [toast, setToast] = useState<DGToastProps>({state: false, severity: "info", text: ""});

    // 关闭控制
    const handleClose = () => {
        // 清空密码信息
        setPassword("");
        // 清空错误信息
        setError({state: false, text: ""});
        // 关闭
        switchView("");
        // 后退
        router(-1);
    }

    // 更改密码信息
    const handleChangePassword: ChangeEventHandler<HTMLInputElement> = (e) => {
        // 清空错误信息
        setError({state: false, text: ""});
        // 设置密码信息
        setPassword(e.target.value);
    }


    // 提交函数
    const handleSubmit = () => {
        // 清空错误信息
        setError({state: false, text: ""});
        // 判断登陆密码是否为空
        if (password === "") return setError({state: true, text: "密码输入不能为空！"});
        // 开始加载
        setLoading(true);
        // 发起登陆请求
        DGConnect.POST(JSON.stringify({
            type: "login", pwd: password, ppAnigol: "逐梦园网站"
        }), result => {
            // 关闭加载
            setLoading(false);
            // 判断错误信息
            if (result["data"]["code"] !== 200) return setError({
                state: true, text: result["data"]["message"] + "错误码：" + result["data"]["code"]
            });
            // 更新本地登陆会话信息
            App!.setUserInfo(result['data']['result']);
            // 刷新主题模式
            ThemeContext!.setThemeMode(true, parseInt(result['data']['result']['theme']));
            // 设置本地存储信息
            const account = Util.Storage.getSession("LOGIN-USERNAME");
            // 将登陆账户和密码存储在本地
            Util.Storage.setLocal("LOGIN-USER", {username: account, password: password})
            // 删除临时记录登陆用户名
            Util.Storage.delSession("LOGIN-EMAIL");
            Util.Storage.delSession("LOGIN-USERNAME");
            // 返回成功信息
            setToast({state: true, severity: "success", text: "登陆成功！"});
            // 关闭面板
            handleClose();
        }, error => {
            // 关闭加载
            setLoading(false);
            // 设置错误信息
            setError({state: true, text: "遇到了一些问题，请尝试重试，或者及时联系我们！错误信息：" + error["stack"]});

        });
    }


    useEffect(() => {
        // 获取登陆信息
        const account = Util.Storage.getLocal("LOGIN-USER");
        // 设置密码信息
        if (account) setPassword(account["password"]);
    }, [state]);

    // DOM 节点
    const ContentView = (<>
        {/* 登录提示语 */}
        <DGTextView Body Bold>
            请输入账户登陆密码，如果您忘记了自己的账户密码，请点击（
            <Button disabled={loading} onClick={() => switchView("forget_index")}>忘记密码</Button>
            ）进行重置密码。
        </DGTextView>
        {/* 隐藏的账号输入框 */}
        <TextField autoComplete="username" variant="standard" disabled={true} style={{display: "none"}}/>
        {/* 密码输入控制器 */}
        <FormControl
            error={error.state}
            disabled={loading}
            margin="dense" variant="standard"
            autoFocus fullWidth required>
            {/* 确认密码提示标语 */}
            <InputLabel>请输入密码</InputLabel>
            {/* 确认密码输入框 */}
            <Input
                autoComplete="new-password"
                value={password}
                onChange={handleChangePassword}
                type={showPwd ? 'text' : 'password'}
                endAdornment={<InputAdornment position="end">
                    {/* 显示、隐藏确认密码图标按钮 */}
                    <IconButton
                        disabled={loading}
                        onClick={() => setShowPwd(!showPwd)}
                        onMouseDown={e => e.preventDefault()}>
                        {/* 显示、隐藏图标 */}
                        {showPwd ? <VisibilityOff/> : <Visibility/>}
                    </IconButton>
                </InputAdornment>}/>
            {/* 确认密码错误信息 */}
            <FormHelperText>{error.text}</FormHelperText>
        </FormControl>
    </>);

    // 返回组件节点
    return (<Box>
        {/* Toast 组件 */}
        <DGToast state={toast} close={() => setToast({state: false, severity: toast.severity, text: toast.text})}/>
        {/* DGDialogLayout 样式 */}
        <DGDialogLayout
            submit={{name: "继续", click: () => handleSubmit()}}
            back={{name: "返回", click: () => switchView("login_index")}}
            title="登录密码" state={state} close={() => handleClose()} load={loading} PANEL AUTO>
            {ContentView}
        </DGDialogLayout>
        {/*DGDrawerLayout 样式 */}
        <DGDrawerLayout
            submit={{name: "继续", click: () => handleSubmit()}}
            more={{name: "返回", click: () => switchView("login_index")}}
            title="登录密码" state={state} close={() => handleClose()} flex="bottom" load={loading} PANEL AUTO>
            {ContentView}
        </DGDrawerLayout>
    </Box>);
}
export default DGLoginPassword;